var fs = require('fs');
var events = require('events');
var http = require('http');
var url = require('url');

// 创建服务器
http.createServer(function (request, response) {

    // 解析请求，包括文件名
    var pathname = url.parse(request.url).pathname;
    //判断 文件类别
    var fileType = pathname.substr(pathname.lastIndexOf('.') + 1);
    // 输出请求的文件名
    console.log("Request for " + pathname + " received.", pathname.substr(1), fileType);
    if (pathname == '/') {
        pathname = '/index.html';
    }
    //文件路径
    var filePath = __dirname + '/pages' + pathname;

    // 从文件系统中读取请求的文件内容
    fs.readFile(filePath, function (err, data) {
        if (err) {
            console.log(err);
            // HTTP 状态码: 404 : NOT FOUND
            // Content Type: text/plain
            response.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' });
            response.write('页面不存在！');
        } else {
            // HTTP 状态码: 200 : OK
            // Content Type: text/plain

            //加上这个样式显示不出来
            //response.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
            switch (fileType) {
                case 'png':
                    response.writeHead(200, { 'Content-Type': 'image/png;charset=utf-8' });
                    break;
                case 'css':
                    response.writeHead(200, { 'Content-Type': 'text/css;charset=utf-8' });
                    break;
                case 'js':
                    response.writeHead(200, { 'Content-Type': 'application/x-javascript;charset=utf-8' });
                    break;
                default:
                    response.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
            }

            if (fileType == 'png' || fileType == 'ico') {
                var stream = fs.createReadStream(filePath);
                var responseData = [];//存储文件流
                if (stream) {//判断状态
                    stream.on('data', function (chunk) {
                        responseData.push(chunk);
                    });
                    stream.on('end', function () {
                        var finalData = Buffer.concat(responseData);
                        response.write(finalData);
                        response.end();
                    });
                }
            } else {
                // 响应文件内容
                response.write(data.toString());

                // 发送响应数据
                response.end();
            }

        }

    });

}).listen(8888);
console.log('Server running at http://127.0.0.1:8888/');